import React, { useCallback, useEffect, useState } from 'react';
import { Button, Form, Select } from 'tea-component';

import useAppStore from '@ide/store';
import { Contract } from '@ide/types/contract';
import { downlaodFileByPath, getContractNameByPath } from '@ide/utils/tools';
import { currentVersion, versionConfig } from '@/config';
import { contractCompile } from '@/api';
import { useIdeStore } from 'ide-plugin';

const platformOptions = [{ value: 'linux_amd64', text: 'linux_amd64' },{ value: 'linux_arm64', text: 'linux_arm64' }];
// if(currentVersion!=='v2.3.0+'){
//   platformOptions.push({
//     value: 'linux_arm', text: 'linux_arm'
//   })
// }

export default function ContractCompile({ style }: {
  style?: React.CSSProperties;
}) {
  const [version, setVersion] = useState<string>(currentVersion);
  const [selectedContract, setSelectedContract] = useState<Contract>();
  const [lang, setLang] = useState<string>('Go');
  const [platform, setPlatform] = useState<string>('linux_amd64');
  
  const [showLoading, setShowLoading] = useState<boolean>(false);
  const [compileResult, setCompileResult] = useState<{ status: 'success' | 'error' | null; file: string; name: string }>({ status: null, file: '', name: '' });

  const { contracts, getContracts } = useAppStore();
  const { currentFileTab } = useIdeStore();
  // 获取合约名称列表
  useEffect(() => {
    if (style?.display === 'block') {
      getContracts();
    }
  }, [getContracts, style?.display]);
  useEffect(() => {
    if (contracts.length) {
      const hasSelectContract = contracts.filter((contract) => contract.contractName === selectedContract?.contractName);
      if (hasSelectContract.length === 0) {
        setSelectedContract(contracts[0]);
      }
    }else{
      setSelectedContract({contractName:''});
    }
  }, [contracts]);

  const updateSelectContract = useCallback((value:string) => {
    setSelectedContract(contracts.find((item) => item.contractName === value));
  }, [contracts]);

  // 选中合约随编辑合约文件变化而变化
  useEffect(() => {
    const currentContractName = getContractNameByPath(currentFileTab?.path);
    if (currentContractName) {
      const hasCurrentContract = contracts.find((contract) => contract.contractName === currentContractName);
      if(hasCurrentContract){
        setSelectedContract(hasCurrentContract);
      }
    }
  }, [currentFileTab]);

  const compileContract = useCallback(async () => {
    if (!selectedContract || !selectedContract.path) {
      return;
    }
    setShowLoading(true);
    setCompileResult({
      status: null,
      file: '',
      name: ''
    });
    contractCompile({
      path: selectedContract.path.endsWith('/') ? selectedContract.path : `${selectedContract.path}/`,
      platform,
      contract_type: lang,
    }).then((res) => {
      if (res.code === 0) {
        setCompileResult({
          status: 'success',
          file: res.data.file,
          name: res.data.file.match(/[^/]+$/)[0]
        });
      } else {
        setCompileResult({
          status: 'error',
          file: '',
          name: ''
        });
      }
    }).finally(() => {
      setShowLoading(false);
    });
    //   console.log('compile contract result: ', result);
    //   setCompileResult({
    //     status: 'success',
    //     file: result.file,
    //     name: result.file.match(/[^/]+$/)[0]
    //   });
    // } catch {
    //   setCompileResult({
    //     status: 'error',
    //     file: '',
    //     name: ''
    //   });
    // }
  }, [selectedContract, platform, lang]);

  const closeCompileResult = () => {
    setCompileResult({
      status: null,
      file: '',
      name: ''
    });
  };

  const downloadCompileResult = useCallback(() => {
    downlaodFileByPath(`${versionConfig.serverHost}file/getContractFile?path=${compileResult.file}`);
  }, [compileResult]);

  return (
    <div style={style} className="nav_tab">
      <Form className='side_tab_form' layout="vertical">
        <Form.Item label="选择合约(编辑中)">
          <Select
            className="set-height"
            size="full"
            matchButtonWidth
            appearance="button"
            options={contracts.map((contract) => ({ value: contract?.contractName || '', text: contract?.contractName }))}
            value={selectedContract?.contractName}
            onChange={updateSelectContract}
          />
        </Form.Item>
        <Form.Item label="长安链版本">
          <Select
            className="set-height"
            size="full"
            matchButtonWidth
            appearance="button"
            options={[{ value: currentVersion, text: currentVersion }]}
            value={version}
            onChange={setVersion}
          />
        </Form.Item>
        {/* for chainmaker */}
        <Form.Item label="合约语言类型">
          <Select
            className="set-height"
            size="full"
            matchButtonWidth
            appearance="button"
            options={[{ value: 'Go', text: 'Go' },{ value: 'EVM', text: 'EVM' }]}
            value={lang}
            onChange={setLang}
          />
        </Form.Item>
        {/* for chainmaker */}
        <Form.Item label="合约执行架构">
          <Select
            className="set-height"
            size="full"
            matchButtonWidth
            appearance="button"
            options={platformOptions}
            value={platform}
            onChange={setPlatform}
          />
        </Form.Item>
        <Button type="primary"
          className="full-btn tea-mt-4n" disabled={showLoading} onClick={compileContract}>合约编译</Button>
      </Form>
      {
        showLoading && (
          <div className="compile-btn-loading">
            <div className="loading-icon"></div>
          </div>
        )
      }

      <div className="compile-result">
        {
          compileResult.status === 'success' && (
            <div className="compile_success">
              <div className="compile_close_icon" onClick={closeCompileResult}></div>
              <div className="compile_icon"></div>
              <div className="compile_file">
                {compileResult.name}
                <span className="compile_download" onClick={downloadCompileResult}></span>
              </div>
              <p>合约编译成功，您可选择在IDE内直接部署或者下载到本地部署。</p>
              {/* <p>合约编译成功</p> */}
            </div>
          )
        }

        {
          compileResult.status === 'error' && (
            <div className="compile_error">
              <div className="compile_close_icon" onClick={closeCompileResult}></div>
              <div className="compile_icon"></div>
              <p>合约编译失败，请重试。</p>
            </div>
          )
        }
      </div>
    </div>
  );
}
